package com.ulife.order.components.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * Created by 文科 on 2015/11/1.
 */
//@Configuration("productMyBatisConfiguration")
//@ConditionalOnClass({EnableTransactionManagement.class})
//@AutoConfigureAfter(DataSourceConfiguration.class)
//@MapperScan(basePackages = {"com.ulife.base.repositories.product"})
public class MyBatisConfiguration implements EnvironmentAware{

    Logger logger = LoggerFactory.getLogger(MyBatisConfiguration.class);

    private RelaxedPropertyResolver propertyResolver = null;

    @Resource(name = "productDataSource") DataSource productDataSource;

    @Override
    public void setEnvironment(Environment environment) {
        propertyResolver = new RelaxedPropertyResolver(environment,"product.mybatis.");
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(){

        logger.debug("Initialization SqlSessionFactory");

        try {
            SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
            sessionFactory.setDataSource(productDataSource);
            sessionFactory.setTypeAliasesPackage(propertyResolver.getProperty("typeAliasesPackage"));
            sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(propertyResolver.getProperty("mapperLocations")));
            //sessionFactory.setConfigLocation(new DefaultResourceLoader().getResource(propertyResolver.getProperty("configLocation")));
            return sessionFactory.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    @Bean
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(productDataSource);
    }

}
